
package com.neo.tiny.bpm.service.process.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.bpm.dto.form.BpmFormFieldRespDTO;
import com.neo.tiny.bpm.entity.BpmFormDO;
import com.neo.tiny.bpm.mapper.BpmFormMapper;
import com.neo.tiny.bpm.service.process.BpmFormService;
import com.neo.tiny.bpm.vo.form.BpmFormCreateReqVO;
import com.neo.tiny.common.constant.ErrorCodeConstants;
import com.neo.tiny.common.exception.WebApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yqz
 * @Description: 工作流的表单定义
 * @date 2022-09-15 23:29:46
 */
@Service
public class BpmFormServiceImpl extends ServiceImpl<BpmFormMapper, BpmFormDO> implements BpmFormService {

    @Autowired
    private BpmFormMapper formMapper;

    @Override
    public Long createForm(BpmFormCreateReqVO vo) {
        checkFields(vo.getFields());

        BpmFormDO bpmForm = BeanUtil.copyProperties(vo, BpmFormDO.class);
        this.save(bpmForm);
        return bpmForm.getId();
    }

    @Override
    public List<BpmFormDO> getFormList(Collection<Long> ids) {
        return formMapper.selectBatchIds(ids);
    }


    /**
     * 校验 Field，避免 field 重复
     *
     * @param fields field 数组
     */
    private void checkFields(List<String> fields) {
        // key 是 vModel，value 是 label
        Map<String, String> fieldMap = new HashMap<>(fields.size() * 2);
        for (String field : fields) {
            BpmFormFieldRespDTO fieldDTO = JSONUtil.toBean(field, BpmFormFieldRespDTO.class);
            Assert.notNull(fieldDTO);
            String oldLabel = fieldMap.put(fieldDTO.getVModel(), fieldDTO.getLabel());
            // 如果不存在，则直接返回
            if (oldLabel == null) {
                continue;
            }
            // 如果存在，则报错
            throw new WebApiException(ErrorCodeConstants.FORM_FIELD_REPEAT);
        }
    }
}
